package com.free.bsf.eureka.client.limitrate;


import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

import com.free.bsf.core.util.PropertyUtils;
import com.free.bsf.eureka.client.EurekaProperties;

import lombok.Data;

@Data
@ConditionalOnProperty(name = "bsf.eureka.limitrate.enabled", havingValue = "true")
@ConfigurationProperties(prefix = "bsf.eureka.limitrate")
public class LimitRateProperties implements InitializingBean{
    
    public static final String DEFAULT="default";
    private Map<String,LimitRateConfig> limitConfigs=new HashMap<String,LimitRateConfig>();
    private Map<String,LimitRateConfig> config;
    

    @Override
    public void afterPropertiesSet() throws Exception {
        if(config!=null) {
            for(LimitRateConfig conf:config.values()) {
                limitConfigs.put(conf.getMethod(), conf);
            }
        }
    }
    public static String getLimitRateAop(){ 
        return PropertyUtils.getPropertyCache(EurekaProperties.BsfEurekaLimitRateAop,"within(@org.springframework.web.bind.annotation.RestController *) ");
    }
    public static boolean getLimitRateEnabled(){
        return PropertyUtils.getPropertyCache(EurekaProperties.BsfEurekaLimitRateEnabled,false);
    }
    public static String[] getLimitRateConfigs(){
        return PropertyUtils.getPropertyCache(EurekaProperties.BsfEurekaLimitRateConfig,new String[0]);
    }
    public static Map<String,LimitRateConfig> getLimitRateConfigs0(){
        return PropertyUtils.getPropertyCache(EurekaProperties.BsfEurekaLimitRateConfig,new HashMap<String,LimitRateConfig>());
    }

    public static int getLimitRateMaxLocalProviderCacheCount(){
        return PropertyUtils.getPropertyCache(EurekaProperties.BsfEurekaLimitRateLocalProviderCacheMaxCount,5000);
    }
    
    public LimitRateConfig parse(String className,String methodName){
        String url = className+"."+methodName;
        LimitRateConfig conf = limitConfigs.get(url);
        if(conf==null){
           if(limitConfigs.containsKey(DEFAULT)) {
                conf = new LimitRateConfig();
                conf.setKey(url);
                conf.setMax(limitConfigs.get(DEFAULT).getMax());
                conf.setPeriod(limitConfigs.get(DEFAULT).getPeriod());
                conf.setProvider(limitConfigs.get(DEFAULT).getProvider());
                conf.setMethod(url);
                limitConfigs.put(url, conf);
                return conf;
           }
           return null;
        }
        else{
            return conf;
        }
    }

}
